from fastapi import APIRouter, Header
from pydantic import BaseModel
from DataModels.database import User, Sync

from DataModels.share import (
    KeyValue,
    RespInfo,
    RespResultCode,
    StatusInfo,
    TokenPayload,
)
from utils.token import check_token, generate_token
from utils.share import timestamp


up_router = APIRouter(prefix="/up")


class UpRequest(BaseModel):
    list: list[KeyValue]


@up_router.post("")
async def up(data: UpRequest, token=Header(None)):
    ok, info = check_token(token)
    if not ok:
        return info
    tk: TokenPayload = info  # type: ignore
    phone = tk.phone
    user = await User.find_one(User.phone == phone)
    if not user:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.PhoneNotFound,
                msg="用户不存在",
            )
        )

    sync = await Sync.find_one(Sync.uid == user.uid)
    if not sync:
        sync = Sync(
            uid=user.uid,
            created=timestamp(),
            data=data.list,
        )
    else:
        sync.data = data.list
    try:
        await sync.save()  # type: ignore
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.Success,
                msg="存储成功",
            ),
            token=generate_token(tk),
        )
    except Exception as _:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.SyncStoreFail,
                msg="存储失败，请重新尝试。",
            )
        )
